<template>
  <div class="user-menu">
    <template v-if="user">
      <el-dropdown trigger="click" @command="onCommand">
        <span class="user-chip">
          <img v-if="user.avatar_url" :src="getAvatarUrl(user.avatar_url)" class="avatar" />
          <div v-else class="avatar placeholder">{{ user.username?.charAt(0)?.toUpperCase() || 'U' }}</div>
          <span class="name">{{ user.username }}</span>
          <el-icon class="caret"><ArrowDown /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">个人中心</el-dropdown-item>
            <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
    <template v-else>
      <button class="login-btn" @click="$emit('login')">登录</button>
    </template>
  </div>
</template>

<script setup>
const props = defineProps({ user: { type: Object, default: null } })
const emit = defineEmits(['logout', 'login'])

const getAvatarUrl = (url) => {
  if (!url) return ''
  // 如果是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  // 如果是本地路径，加上API基础URL
  return `http://localhost:8000${url}`
}

const onCommand = (cmd) => {
  if (cmd === 'logout') emit('logout')
  if (cmd === 'profile') {
    // 跳转到个人中心
    window.location.href = '/profile'
  }
}
</script>

<style scoped>
.user-menu { display: flex; align-items: center; }
.user-chip { display: inline-flex; align-items: center; cursor: pointer; padding: 2px 8px; background: rgba(255,255,255,0.6); border: 1px solid #e2e8f0; border-radius: 999px; transition: background .25s; }
.user-chip:hover { background: #fff; }
.avatar { width: 28px; height: 28px; border-radius: 50%; object-fit: cover; margin-right: 6px; }
.avatar.placeholder { display:flex; align-items:center; justify-content:center; font-weight:600; background:#6366f1; color:#fff; }
.name { font-size: 13px; margin-right: 4px; }
.caret { font-size: 14px; color:#666; }
.login-btn { cursor:pointer; border:none; outline:none; padding:8px 18px; font-size:13px; font-weight:600; letter-spacing:.5px; border-radius:999px; background:linear-gradient(120deg,#c8102e,#e8576b 50%,#f4a261); color:#fff; box-shadow:0 4px 14px -4px rgba(200,16,46,0.55); transition:.35s; }
.login-btn:hover { filter:brightness(1.06); transform:translateY(-2px); box-shadow:0 10px 24px -6px rgba(200,16,46,0.55); }
.login-btn:active { transform:translateY(0); }
</style>
